package com.ylm.eduservice.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ylm.baseservice.handler.EducationException;
import com.ylm.eduservice.entity.EduSubject;
import com.ylm.eduservice.entity.vo.ExcelSubjectData;
import com.ylm.eduservice.service.EduSubjectService;

public class SubjectExcelListener extends AnalysisEventListener<ExcelSubjectData> {

    public EduSubjectService subjectService;

    public SubjectExcelListener(){}

    public SubjectExcelListener(EduSubjectService subjectService){
        this.subjectService=subjectService;
    }

    private EduSubject existOneSubject(EduSubjectService subjectService,String name){
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id","0");
        wrapper.eq("title",name);
        EduSubject eduSubject = subjectService.getOne(wrapper);
        return eduSubject;
    }

    private EduSubject existTwoSubject(EduSubjectService subjectService, String name, String pid){
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", pid);
        wrapper.eq("title", name);
        EduSubject eduSubject = subjectService.getOne(wrapper);
        return eduSubject;
    }

    // 业务逻辑核心
    @Override
    public void invoke(ExcelSubjectData excelSubjectData, AnalysisContext analysisContext) {
        //1 读取数据验证是否空值
        if (excelSubjectData == null){
            throw new EducationException(20001,"导入课程分类失败");
        }
        //2 判断一级分类名称是否重复
        EduSubject existOneSubject = this.existOneSubject(subjectService,excelSubjectData.getOneSubjectName());
        //3 一级分类不重复插入数据库
        if(existOneSubject==null){
            existOneSubject = new EduSubject();
            existOneSubject.setTitle(excelSubjectData.getOneSubjectName());
            existOneSubject.setParentId("0");
            subjectService.save(existOneSubject);
        }
        String pid = existOneSubject.getId();
        //4 判断二级名称是否重复
        EduSubject existTwoSubject = this.existTwoSubject(subjectService,excelSubjectData.getTwoSubjectName(), pid);
        //5 二级不重复插入数据库
        if(existTwoSubject == null){
            existTwoSubject = new EduSubject();
            existTwoSubject.setTitle(excelSubjectData.getTwoSubjectName());
            existTwoSubject.setParentId(pid);
            subjectService.save(existTwoSubject);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
